import store from '@/store'
import routers from '@/router/routers'
import { Routers } from '@/router/routers'
import { asyncRoutes } from '@/router/asyncRoutes.js'
console.log('asyncRoutes', asyncRoutes);

// 完善路由
const routerRes = data => {
  console.log('完善信息路由', data);
  data.forEach(item => {
    if (item.children && item.children.length) {
      let children = JSON.parse(JSON.stringify(item.children));
      
      item.children = [
        {
          path: item.name,
          name: item.name,
          meta: {
            hideInMenu: true,
            title: item.meta.title,
          },
          component: item.name,
          children: children,
        },
      ]
    }else{
      item.children = [
        {
          path: item.name,
          name: item.name,
          meta: {
            hideInMenu: true,
            title: item.meta.title,
          },
          component: item.name,
          children: [],
        },
      ]
    }
  })
  storageRouter(data)
}

const storageRouter = data => {
  localStorage.routers = JSON.stringify(data)
  store.commit(
    'setShowRouter',
    localStorage.routers
      ? [...routers,  ...JSON.parse(localStorage.routers)]
      : routers
  )
}

// 获取路由
function getObjArr(router, i, routerList) {
  console.log('路由router', router);
  console.log('routerList', routerList)
  if (!localStorage.routers) {
    // 清除所有緩存
    localStorage.clear()
    localStorage.routers = JSON.stringify([])
  }
  // localStorage 获取数组对象的方法
  if (i === 1 && JSON.parse(localStorage.routers).length < 1) {
    return router
  } else if (
    i === 1 &&
    JSON.parse(localStorage.routers).length > 0 &&
    routerList
  ) {
    return [
      ...router,
      ...filterAsyncRouter(JSON.parse(localStorage.routers), asyncRoutes)
    ]
  } else if (JSON.parse(localStorage.routers).length !== 0 && routerList) {
    // eslint-disable-next-line no-undef
    return [
      ...filterAsyncRouter(JSON.parse(localStorage.routers), asyncRoutes)
    ]
  }
}

// 处理component
function filterAsyncRouter(newRouter = [], asyncRoutes = []) {
  console.log('权限路由', newRouter);
  console.log('全部动态路由', asyncRoutes);
  let arr = []
  asyncRoutes.forEach((v, i) => {
    console.log('v', v);
    newRouter.forEach((item, index) => {
      if (item.name === v.name) {
        if (item.children && item.children.length > 0) {
          v.children = filterAsyncRouter(item.children, v.children)
        }
        arr.push(v)
      }
    })
  })
  console.log('arr', arr);
  localStorage.setItem('routerList', JSON.stringify(arr))
  return arr
}
// function filterAsyncRouter(oldRouter, newRouter, routerList) {
//   // console.log('静态路由', oldRouter);
//   // console.log('动态路由', newRouter);
//   // console.log('全部路由', routerList);
//   let outputValue = newRouter.map(item => {
//     // console.log('routerList', routerList.item.component);
//     const obj = {}
//     for(let key in routerList) {
//       obj[key] = key
//     }
//     if (typeof item.component === 'string' && obj[item.component]) {
//       console.log('ok');
//       item.component = obj[item.component]
//     } else {
//       item.component = null
//     }

//     if (item.children && item.children.length > 0) {
//       filterAsyncRouter(oldRouter, item.children, routerList)
//     }
//     return item
//   })
//   console.log('筛选之后的菜单', outputValue);
//   // store.commit('setData', outputValue)
//   // console.log(store);
//   return outputValue
// }

// 权限数据处理
const accessOpen = data => {
  const accessArray = data.map(item => {
    return item.name
  })
  return accessArray
}

const typeOf = obj => {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  return map[toString.call(obj)]
}

const deepCopy = data => {
  const t = typeOf(data)
  let o

  if (t === 'array') {
    o = []
  } else if (t === 'object') {
    o = {}
  } else {
    return data
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(deepCopy(data[i]))
    }
  } else if (t === 'object') {
    for (let i in data) {
      o[i] = deepCopy(data[i])
    }
  }
  return o
}

const copyText = text => {
  return new Promise((resolve, reject) => {
    try {
      const input = document.createElement('input')
      document.body.appendChild(input)
      input.setAttribute('value', text)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
      }
      document.body.removeChild(input)
      resolve(true)
    } catch (err) {
      reject(err)
    }
  })
}

// 节流防抖(只有防抖   可以考虑做个升级版 )
const touchByMistake = (fn, condition, time = 500) => {
  if (condition.repeatClick) {
    if (condition.timeRepeat) {
      clearTimeout(condition.timeRepeat)
    }
    condition.timeRepeat = setTimeout(() => {
      condition.repeatClick = false
    }, time)
  } else {
    condition.repeatClick = true
    condition.timeRepeat = setTimeout(() => {
      condition.repeatClick = false
    }, time)
    if (fn) {
      fn()
    }
  }
}
// if (this.repeatClick) {
//   if (this.timeRepeat) {
//     clearTimeout(this.timeRepeat)
//   }
//   this.timeRepeat = setTimeout(() => {
//     this.repeatClick = false
//   }, 500)
// } else {
//   this.repeatClick = true
//   this.timeRepeat = setTimeout(() => {
//     this.repeatClick = false
//   }, 500)
//   this.$emit('drawerSubmit')
// }

export default {
  routerRes,
  storageRouter,
  getObjArr,
  accessOpen,
  deepCopy,
  typeOf,
  copyText,
  touchByMistake
}
